class MessagesController < ApplicationController
  before_filter :login_required
  before_filter :check_unread
  
  def index
    redirect_to :action => :inbox
  end
  
  def new
    if params[:to]
      @message = Message.new :receiver_ids => params[:to]
      render :action => 'send_to'
    else
      @message = Message.new
    end
  end
  
  def create
    @message = Message.new params[:message]
    @message.sender = current_user
    
    @message.save
    if @message.errors.empty?
      flash[:notice] = 'message sent successfully.'
      
      respond_to do |format|
        format.html { redirect_to message_url(@message, :type => 'outbox') }
        format.js
      end
    else
      render :action => :new
    end
  end
  
  def show
    @thread = Message.find params[:id]
    if show_del?
      @messages = @thread.messages
    else
      case params[:type] || 'inbox'
      when 'inbox'
        @messages = current_user.inbox_messages.find_all_by_thread_id @thread.id
        InboxItem.mark_read current_user, @thread.id
      when 'outbox'
        @messages = current_user.outbox_messages.find_all_by_thread_id @thread.id
      else
        
      end
    end
  end
  
  def destroy
    current_user.box_items.find_all_by_thread_id(params[:id]).each do |item|
      mark_for_destruction item, params[:type]
    end
    flash[:notice] = "1 threads deleted."
    redirect_to :action => current_box
  end
  
  def inbox
    @box_threads = current_user.inbox_threads
  end
  
  def outbox
    @box_threads = current_user.outbox_threads
  end
  
  def do_selected
    respond_to do |format|
      unless params[:to_delete].blank?
        if params[:mark_read_button] # mark as read
          InboxItem.mark_read_all current_user, params[:to_delete]
        elsif params[:mark_unread_button] # mark as unread
          InboxItem.mark_unread_all current_user, params[:to_delete]
        else # delete
          params[:to_delete].each do |thread_id|
            current_user.box_items.find_all_by_thread_id(thread_id).each do |item|
              mark_for_destruction item, params[:type]
            end
          end
          flash[:notice] = "#{params[:to_delete].size} threads deleted."
        end
      end
      format.html { redirect_to :action => current_box }
      format.js # TODO
    end
  end
  
  private 
  def current_box
    params[:type] || 'inbox'
  end
  
  def show_del?
    params[:show_del] && params[:show_del] == '1'
  end
  
  def check_unread
    @count_unread = InboxItem.count :thread_id, :conditions => { :user_id => current_user.id, :read_at => nil }, :distinct => true
  end
  
  def mark_for_destruction(item, type)
    case type
    when 'inbox': item.update_attribute :inbox_deleted, true
    when 'outbox': item.update_attribute :outbox_deleted, true
    else 
      return
    end
    
    item.purge
  end
end
